import socket,sys,os
import select
from time import time, ctime
from threading import *

conn_client={}

mySocketReception=None
mySocketEmission=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
thReception=None
#port=0

class Serveur:
    
    def __init__(self):
        mySocketReception=socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
	mySocketEmission=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

        try: 
            mySocketReception.bind(('localhost',port))

        except socket.error:
            print "La liaison a echouee"
            sys.exit()
        
        while 1:
            mySocketReception.listen(5)

        # en attente qu'un client se connecte
            (newsock, addr) = mySocketReception.accept()
            print "connection entrante : %s:%d" % addr

        # on lit ce que la socket a ecrit
            
            thReception=ThreadReception(newsock)
            print "threadReception initialisee 3"
            thReception.start()
          
            it=thReception.getName()
            conn_client[it]=newsock

            
        thReception.stop()    
        mySocketReception.close()
        mySocketEmission.close()
    

class ThreadReception(Thread):
     def __init__(self,connexion):
         print "threadReception initialisee"
         Thread.__init__(self)
         self.connexion=connexion
         print "threadReception initialisee 2"
         self.running=True
          
     def run(self):
         while self.running:
             msgClient=self.connexion.recv(1024)
             print msgClient
             
             if msgClient=="clientPret":
                 try: 
                     mySocketEmission.connect(('localhost',port+1))
                 except socket.error:
                     print "La liaison a echouee"
                     self.running=False
                     
             print "Possibilite d'envoi au client"

             while self.running:    
                 msg = raw_input('>> ')
	# envoi puis reception de la reponse
                 mySocketEmission.send(msg)
                                  
         self.connexion.close()
     
     def stop(self):
         self.running=False
         
class GestionJeu():

    def creer_partie(self,idjoueur1,maxjoueur):
        self.listejoueur

    def list_partie(self):
        return listparties
    
#    def list_joueur
    
    


if __name__=="__main__":
    import sys
    try:
        if len(sys.argv)<2:
            print "usage : %s <port>" % (sys.argv[0],)
            sys.exit(-1)
        port=int(sys.argv[1])
        Serveur()
        thReception.join()
    except:
        thReception.running=False

    

